/**
 * Copyright (c) 2005 - 2007 FeyaSoft Corp. All Rights Reserved.
 */
package com.feyaSoft.home.services.source;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;

import com.feyaSoft.home.web.source.DirFile;
import com.feyaSoft.home.web.source.Fold;
import com.feyaSoft.home.web.source.SourceJson;

/**
 * @author Fenqiang Zhuang
 * @Oct 8, 2007
 * 
 * This file is used to .....
 */
public class SourceServiceImpl implements SourceService {
	// log file
	private final static Logger log = Logger.getLogger(SourceServiceImpl.class);

	private List dirFiles = new ArrayList();
	private List folds = new ArrayList();
	private String rootFile = "/opt/applications";

	/**
	 * Get a list of files now
	 * 
	 * @param node
	 * @return
	 * @throws Exception
	 */
	public SourceJson getFiles(String node) throws Exception {
		if (node != null && node.length() > 0) {
			rootFile = node;
		}

		SourceJson sourcesJson = new SourceJson();

		try {
			// file the fold/files now
			File aStartingDir = new File(rootFile);
			getFileListing(aStartingDir);

			sourcesJson.setFileNames(dirFiles);
			sourcesJson.setFoldNames(folds);

			aStartingDir = null;
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}

		return sourcesJson;
	}

	public void getFileListing(File aStartingDir) throws FileNotFoundException {
		dirFiles = new ArrayList();
		folds = new ArrayList();

		File[] filesAndDirs = aStartingDir.listFiles();
		List filesDirs = Arrays.asList(filesAndDirs);

		Iterator filesIter = filesDirs.iterator();
		File file = null;
		while (filesIter.hasNext()) {
			file = (File) filesIter.next();

			// check file is dir
			if (file.isFile()) {
				String fullPathName = file.getAbsolutePath();
				DirFile dirFile = new DirFile();
				dirFile.setText(file.getName());
				dirFile.setId(fullPathName);
				dirFiles.add(dirFile);
			}

			// check file is file
			if (file.isDirectory()) {
				String dirName = file.getAbsolutePath();
				Fold fold = new Fold();
				fold.setText(file.getName());
				fold.setId(dirName);
				folds.add(fold);
			}
		}
	}
}
